package com.hnkywl.sts.webservice.wly.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.entity.djgl.Jydd;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.fxssh.DdzyfwService;
import com.hnkywl.sts.util.Tools;
import com.hnkywl.sts.util.XmlUtil;
import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import com.hnkywl.sts.webservice.wly.IOrderResource;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * 订单及资源相关接口
 * Created by Fei on 2015/12/10.
 */
@Service
public class OrderResourceService implements IOrderResource, ApplicationContextAware {

    // 获取接口配置
    static ResourceBundle res = ResourceBundle.getBundle("webservice");

    private ApplicationContext applicationContext;
    private DdzyfwService ddzyfwService;//订单及资源相关接口service
    private WebserviceLogService webserviceLogService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        ddzyfwService = (DdzyfwService) applicationContext.getBean("ddzyfwService");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    /**
     * 查询销售单赎货订单信息
     *
     * @param param
     * @return
     */
    @Override
    public String querySaleOrderInfo(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String orderId = Tools.NullToString(resultMap.get("order_id"));
            if (StringUtils.isBlank(orderId)) {
                result = "[]";
            } else {
                result = this.ddzyfwService.findXsdInfo(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
            result = "[]";
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "querySaleOrderInfo",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "querySaleOrderInfo",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 销售系统推送资源物资到运营系统
     *
     * @param param
     * @return
     */
    @Override
    public String pushResources(String sellerName, String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            List<Map<String, Object>> list = gson.fromJson(param, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            if (null != list && list.size() > 0) {
                result = this.ddzyfwService.saveGd(sellerName, list);
            } else {
                result = "[{\"code\":\"1\",\"msg\":\"成功!\"}]";
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "[{\"code\":\"1\",\"msg\":\"运营系统返回，" + e.getMessage() + "\"}]";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushResources",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushResources",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 交易系统向运营系统推送交易订单
     *
     * @param param json格式字符串
     * @return
     */
    @Override
    public String pushTradingOrder(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Type type = new TypeToken<List<Jydd>>() {
            }.getType();
            List<Jydd> list = gson.fromJson(param, type);
            if (null != list && list.size() > 0) {
                String nbgsName = res.getString("sellName");//运营商，内部公司，原来物流系统称为物流方公司，默认‘成都积微物联电子商务有限公司’
                String supplierName = res.getString("supplier");//赎货供应商，企业机构，默认‘攀钢集团国际经济贸易有限公司成都分公司’
                Jydd jydd = list.get(0);//因为每次只推送一条,所以直接取第一条
                if ("mid".equals(jydd.getExtension())) {
                    result = this.ddzyfwService.saveJydd(jydd, supplierName, res.getString("warehouse"), res.getString("pmcode"), false, nbgsName);
                } else if ("normal".equals(jydd.getExtension()) || StringUtils.isEmpty(jydd.getExtension())) {
                    // 判断是否，是赎货订单
                    if (StringUtils.equals(jydd.getDingdan_type(), "1")) {
                        if (StringUtils.equals(nbgsName, jydd.getSeller_name())) {
                            result = this.ddzyfwService.saveJydd(jydd, supplierName, res.getString("warehouse"), res.getString("pmcode"), true, nbgsName);
                        } else {
                            result = "[{\"code\":\"1\",\"message\":\"运营系统返回，未支持的赎货运营商:" + jydd.getSeller_name() + "\"}]";
                        }
                    } else {
                        // 普通订单
                        result = this.ddzyfwService.saveJydd(jydd, null, null, null, false, null);
                    }
                } else {
                    result = "[{\"code\":\"1\",\"message\":\"运营系统返回，未支持的extension值:" + jydd.getExtension() + "\"}]";
                }
            } else {
                result = "[{\"code\":\"1\",\"message\":\"运营系统返回，没有数据！\"}]";
            }
        } catch (RuntimeException e) {
            result = "[{\"code\":\"1\",\"message\":\"运营系统返回，" + e.getMessage() + "\"}]";
            exception = StackTraceUtil.getStackTrace(e);
        } catch (Exception e) {
            result = "[{\"code\":\"1\",\"message\":\"运营系统返回，" + e.getMessage() + "\"}]";
        }
        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushTradingOrder",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushTradingOrder",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }


    /**
     * 交易系统，查询居中结算订单是否已经支付货款
     *
     * @param param
     * @return
     */
    @Override
    public String queryPayment(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String order_sn = Tools.NullToString(resultMap.get("order_sn"));
            if (StringUtils.isBlank(order_sn)) {
                result = "{\"code\":\"1\",\"message\":\"订单号为空！\"}";
            } else {
                result = this.ddzyfwService.queryContractPayment(order_sn);
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"message\":\"运营系统返回，" + e.getMessage() + "\"}";
        }

        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushTradingOrder",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "pushTradingOrder",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }

        return result;
    }


    /**
     * 交易系统撤单
     *
     * @param param
     * @return
     */

    @Override
    public String cancelResourceGoods(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            List<Map<String, Object>> resultList = gson.fromJson(param, new TypeToken<List<Map<String, Object>>>() {
            }.getType());
            if (null != resultList && resultList.size() > 0) {
                result = ddzyfwService.cancelGoodsOrder(resultList);
            } else {
                result = "[{\"code\":\"1\",\"message\":\"数据为空\"}]";
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "[{\"code\":\"1\",\"message\":\"" + exception + "\"}]";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "cancelResourceGoods",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "cancelResourceGoods",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 取消交易订单<br/>A20160427zhp
     */
    @Override
    public String cancelJydd(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> paraMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String order_sn = (String) paraMap.get("order_sn");
            if (null != order_sn && !"".equals(order_sn)) {
                String msg = ddzyfwService.cancelJydd(order_sn);
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("code", "0");
                resultMap.put("message", msg);
                return new Gson().toJson(new Object[]{resultMap});
            } else {
                result = "[{\"code\":\"1\",\"message\":\"数据为空\"}]";
            }
        } catch (Exception e) {
            exception = e.getMessage();
            result = "[{\"code\":\"1\",\"message\":\"" + exception + "\"}]";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONArray jsonArray = new JSONArray(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "cancelResourceGoods",
                    jsonArray.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "cancelResourceGoods",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 销售系统推送结算信息（统计成交量用）
     *
     * @param param
     * @return
     */
    @Override
    public String pushXsSettleInfo(String param) {
        String reCode = "0";
        String reMsg = "";
        String result = "";
        String exception = null;
        try {
            reMsg = this.ddzyfwService.saveXsSettleInfo(param);
        } catch (Exception e) {
            reCode = "-1";
            reMsg = e.getMessage();
            e.printStackTrace();
            exception = StackTraceUtil.getStackTrace(e);
        }

        result = XmlUtil.getReturnXml("XSDH009", reCode, reMsg);
        webserviceLogService.saveServerLog(
                OrderResourceService.class.getName(),
                "pushXsSettleInfo",
                param,
                "返回结果：" + result,
                exception,
                ""
        );
        return result;
    }

    /**
     * 接收销售系统订单信息（统计挂牌量用）
     *
     * @param param
     * @return
     */
    public String pushXsOrderInfo(String param) {
        String reCode = "0";
        String reMsg = "";
        String result = "";
        String exception = null;
        try {
            reMsg = this.ddzyfwService.saveXsOrderInfo(param);
        } catch (Exception e) {
            e.printStackTrace();
            reCode = "-1";
            reMsg = e.getMessage();
            exception = StackTraceUtil.getStackTrace(e);
        }

        result = XmlUtil.getReturnXml("XSDH008", reCode, reMsg);
        webserviceLogService.saveServerLog(
                OrderResourceService.class.getName(),
                "pushXsOrderInfo",
                param,
                "返回结果：" + result,
                exception,
                ""
        );
        return result;
    }

    /**
     * 交易系统查询销售系统挂牌量
     *
     * @param param
     * @return
     */
    @Override
    public String queryXsOrderWt(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String dateStart = Tools.NullToString(resultMap.get("date_start"));
            String dateEnd = Tools.NullToString(resultMap.get("date_end"));
            result = this.ddzyfwService.countOrderWt(dateStart, dateEnd);
        } catch (Exception e) {
            e.printStackTrace();
            result = "{\"code\":\"1\",\"message\":\"" + e.getMessage() + "\"}";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsOrderWt",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsOrderWt",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 查询指定日期的销售系统最新订单
     */
    @Override
    public String queryXsOrderItems(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String orderDate = Tools.NullToString(resultMap.get("orderDate"));
            result = ddzyfwService.getXSOrderItems(orderDate);
        } catch (Exception e) {
            e.printStackTrace();
            exception = e.getMessage();
            result = "{\"code\":\"1\",\"message\":\"" + e.getMessage() + "\"}";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsOrderItems",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsOrderItems",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }

    /**
     * 交易系统查询销售系统成交量
     *
     * @param param
     * @return
     */
    @Override
    public String queryXsSettleWt(String param) {
        String result;
        String exception = null;
        try {
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(param, new TypeToken<Map<String, Object>>() {
            }.getType());
            String dateStart = Tools.NullToString(resultMap.get("date_start"));
            String dateEnd = Tools.NullToString(resultMap.get("date_end"));
            result = this.ddzyfwService.countSettleWt(dateStart, dateEnd);
        } catch (Exception e) {
            e.printStackTrace();
            result = "{\"code\":\"1\",\"message\":\"" + e.getMessage() + "\"}";
            exception = StackTraceUtil.getStackTrace(e);
        }
        try {
            JSONObject jsonObject = new JSONObject(param);
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsSettleWt",
                    jsonObject.toString(),
                    "返回结果：" + result,
                    exception,
                    ""
            );
        } catch (Exception e) {
            webserviceLogService.saveServerLog(
                    OrderResourceService.class.getName(),
                    "queryXsSettleWt",
                    param,
                    "返回结果：" + result,
                    exception,
                    ""
            );
        }
        return result;
    }
}
